/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

<template>
  <div class='adaptive-layout'>
    <NavigationContainerVue
      :mode='mode'
      :navigationPageName='navigationPageName'
      :navBarWidth='navBarWidth'
      :navBarWidthRange='navBarWidthRange'
      :minContentWidth='minContentWidth'
      :navBarPosition='navBarPosition'
      :onNavigationModeChange='onNavigationModeChange'
    >
      <NavigationBarVue>
        <TabBarContainerVue>
          <TabBarContentVue>
            <div class='list-container'>
              <div class='container' :style='{ paddingTop: `${topAvoidArea}px`, height: `calc(100% - ${topAvoidArea}px)` }'>
                <!-- 头部标题区域 -->
                <div class='title-wrap'>
                  <div class='title-info'>
                    <div class='go-back' @click='goHome'>
                      <img
                        class='title-img'
                        src='../../assets/images/left.png'
                      />
                    </div>
                    <div class='title-link'>
                      <span class='title'>消息</span>
                    </div>
                  </div>
                  <div class='icon-wrap'>
                    <template>
                      <img
                        class='title-img'
                        :src="require('../../assets/images/search.png')"
                        alt='搜索'
                      />
                      <img
                        class='title-img'
                        :src="require('../../assets/images/add.png')"
                        alt='添加'
                        :style="{ marginLeft: '8px' }"
                      />
                    </template>
                  </div>
                </div>
                <!-- 消息列表 -->
                <ul class='content message-list'>
                  <li
                    v-for='item in messageDataList'
                    :key='item.id'
                    class='message-item'
                    :class="{ 'item-active': activeItem.id === item.id }"
                    @click='handleMessageClick(item)'
                  >
                    <div class='item'>
                      <!-- 头像区域 -->
                      <div class='item-img-wrap'>
                        <img
                          class='item-img'
                          :src='item.avatar'
                          :alt='item.name'
                        />
                        <!-- 未读标记 -->
                        <div
                          v-if='item.unread'
                          class='unread-bubble-wrap'
                          :class="{
                            numerical: typeof item.unread === 'number',
                            dot: typeof item.unread !== 'number',
                          }"
                        >
                          <span class='unread-bubble'>{{ item.unread }}</span>
                        </div>
                      </div>
                      <!-- 消息内容区域 -->
                      <div class='item-content'>
                        <div class='content-main'>{{ item.name }}</div>
                        <div class='content-secondary'>{{ item.message }}</div>
                      </div>
                      <!-- 时间 -->
                      <div class='item-time'>{{ item.time }}</div>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </TabBarContentVue>
          <TabBarVue
            :width='widthTab'
            :height='heightTab'
            bgColor='rgb(241, 243, 245)'
            :selectedColor='selectedColor'
            :unselectedColor='unselectedColor'
            :onTabItemClick='handleClickTable'
            value='0'
          >
            <TabBarItemVue
              v-for='(item, index) in navItems'
              :name='index'
              :key='index'
            >
            <div class='tab-center' :style='{ marginBottom: `${bottomAvoidArea}px` }'>
              <img
                class='toolbar-icon'
                :src='require(`@/assets/images/${item.icon}.svg`)'
                :alt='item.title'
              />
              <div
                :class="[
                  'toolbar-title',
                  index === 0 ? 'toolbar_info' : '',
                  { active: item.active },
                ]"
              >
                {{ item.title }}
              </div>
            </div>
            </TabBarItemVue>
          </TabBarVue>
        </TabBarContainerVue>
      </NavigationBarVue>
      <NavigationContentVue></NavigationContentVue>
    </NavigationContainerVue>
  </div>
</template>

<script setup lang='ts'>
import { BreakpointManager } from '@hadss/web_adaptive_layout_ui';

import {
  NavigationContainerVue,
  NavigationContentVue,
  NavigationBarVue,
  TabBarContainerVue,
  TabBarContentVue,
  TabBarVue,
  TabBarItemVue,
} from '@hadss/web_adaptive_layout_vue3';
import { messageData } from '../../mocks/mockData';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { ref, onMounted, onBeforeUnmount, computed, reactive } from 'vue';
import { AvoidArea, AvoidAreaInfo, AvoidAreaType } from '@/common/windowCommon';

const router = useRouter();
const route = useRoute();
const store = useStore();
const breakpointManager = new BreakpointManager();
const navItems = [
  { icon: 'xiaoxi', title: '消息', active: true },
  { icon: 'txl', title: '通讯录', active: true },
  { icon: 'sjq', title: '社交圈', active: true },
  { icon: 'my', title: '我的', active: true },
];

const currentBp = ref<string>('sm');
const messageDataList = ref(messageData);
const mode = ref<string>('Auto');
const navBarWidth = ref<number>(570);
const selectedColor = ref<string>('rgb(10, 89, 247)');
const unselectedColor = ref<string>('rgba(0, 0, 0, 0.6)');
const navigationPageName = ref<string>('MessageList');
const navBarWidthRange = ref<number[]>([260, 570]);
const minContentWidth = ref<number>(340);
const navBarPosition = ref<string>('Start');
const currentMode = ref('');
const activeItem = ref({
  id: '11',
  name: '张晓萌',
  message: '好的，我明天过来',
  time: '13:55',
  avatar: require('../../assets/images/touxiang.svg'),
  unread: null,
});
const topAvoidArea = ref(0);
const bottomAvoidArea = ref(0);

const unsubscribe = ref(null);

const goHome = (): void => {
  if (currentMode.value === 'Split' && route.path === '/messageList/detailContainer') {
    router.go(-2);
  } else {
    router.back();
  }
};

const handleClickTable = (tab: any): void => {
  if (tab.index === 0) {
    selectedColor.value = 'rgb(10, 89, 247)';
  } else {
    selectedColor.value = 'rgba(0, 0, 0, 0.6)';
  }
};

const handleMessageClick = (item: any): void => {
  activeItem.value = item;
  store.commit('updateItem', item);
  if (route.path === '/messageList') {
    router.push({
      path: '/messageList/detailContainer',
      params: {
        activeItem: JSON.stringify(item),
      },
    });
  }
};

const handleAvoidAreaChange = (event: any): void => {
  const data = event.detail as AvoidAreaInfo;
  const areaType = data.type;
  if (areaType === AvoidAreaType.TYPE_SYSTEM) {
    topAvoidArea.value = (window as any).webClass?.pxToVp(data.area.topRect.height);
  }
  if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
    bottomAvoidArea.value = (window as any).webClass?.pxToVp(data.area.bottomRect.height);
    Object.assign(heightTab, {
      md: `${56 + bottomAvoidArea.value}px`,
      lg: '100%'
    });
  }
};

const onNavigationModeChange = (mode: string): void => {
  currentMode.value = mode;
  if (mode === 'Split' && route.path !== '/messageList/detailContainer') {
    router.push('/messageList/detailContainer');
  }
};

const widthTab = computed(() => {
  return ['lg', 'xl'].includes(currentBp.value) ? '96px' : '100%';
});

const heightTab = reactive({
  md: '56px',
  lg: '100%'
});

onMounted(() => {
  store.commit('updateItem', activeItem.value);
  unsubscribe.value = breakpointManager.subscribeToBreakpoint((vp: string) => {
    currentBp.value = vp;
    store.commit('updateCurrentBp', currentBp.value);
  });
  if ((window as any).webClass) {
    const webClass = (window as any).webClass;
    const topArea = webClass.getAvoidArea(AvoidAreaType.TYPE_SYSTEM) as AvoidArea;
    const bottomArea = webClass.getAvoidArea(AvoidAreaType.TYPE_NAVIGATION_INDICATOR) as AvoidArea;
    topAvoidArea.value = webClass.pxToVp(topArea.topRect.height);
    bottomAvoidArea.value = webClass.pxToVp(bottomArea.bottomRect.height);
    Object.assign(heightTab, {
      md: `${56 + bottomAvoidArea.value}px`,
      lg: '100%'
    });
  }
  window.addEventListener('avoidAreaChange', handleAvoidAreaChange);
});

onBeforeUnmount((): void => {
  if (unsubscribe.value) {
    unsubscribe.value();
  }
  window.removeEventListener('avoidAreaChange', handleAvoidAreaChange);
});
</script>

<style lang='less' scoped>
@import './MessageList.less';
</style>
